<template>
  <div v-if="isNew" style="margin: 50px">
    <el-form style="max-width: 700px;margin-left: 20%" label-width="auto">
      <el-form-item label="客户" required>
        <el-button type="info" @click="openChooseCusDialog">选择客户</el-button>
        <el-table v-if="selectedCustomer.length > 0" :data="selectedCustomer">
          <el-table-column prop="cusId" label="客户编号" width="80"/>
          <el-table-column prop="cusName" label="客户姓名" width="100"/>
          <el-table-column prop="phone" label="客户电话" width="150"/>
          <el-table-column prop="address" label="客户地址" width="100" show-overflow-tooltip/>
          <!--删除按钮-->
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="danger" icon="delete" circle plain size="mini" @click="deleteCustomer(row.cusId)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="销售人员" required>
        <el-button type="info" @click="openChooseEmpDialog">选择销售人员</el-button>
        <el-table v-if="selectedEmployee.length > 0" :data="selectedEmployee" style="align-content: center">
          <el-table-column prop="empId" label="销售人员编号" width="110"/>
          <el-table-column prop="empName" label="销售人员姓名" width="150"/>
          <el-table-column prop="phone" label="销售人员电话" width="150"/>
          <el-table-column label="操作" width="100" show-overflow-tooltip>
            <template #default="{row}">
              <el-button type="danger" icon="delete" circle plain size="mini" @click="deleteEmployee(row.empId)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="合同状态" required>
        <el-select v-model="newContract.contractStatus" placeholder="请选择合同状态">
          <el-option v-for="item in contractStatusOptions"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同签订日期" prop="contractDate" required>
        <el-date-picker
            v-model="newContract.contractDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"/>
      </el-form-item>
      <el-form-item label="合同结束日期">
        <el-date-picker v-model="newContract.contractEndDate"
                        type="date"
                        placeholder="选择日期"
                        value-format="YYYY-MM-DD"
                        style="width: 100%"/>
      </el-form-item>
      <el-form-item label="合同商品选择" required>
        <el-button type="primary" @click="openChooseProductDialog">选择商品</el-button>
        <el-table v-if="newContract.products.length > 0" :data="newContract.products">
          <el-table-column prop="productId" label="商品编号" width="100"/>
          <el-table-column prop="productName" label="商品名称" width="120"/>
          <el-table-column prop="price" label="商品单价" width="100"/>
          <el-table-column label="商品数量" width="180">
            <template #default="{row}">
              <el-input-number v-model="row.quantity" :min="1" :max="1000"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template #default="{row}">
              <el-button type="danger" icon="delete" circle plain size="mini" @click="deleteProduct(row.productId)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="合同备注">
        <el-input type="textarea" v-model="newContract.remark" placeholder="请输入合同备注"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <!-- 使用 flexbox 来居中按钮 -->
    <div style="display: flex; justify-content: center; width: 100%;">
      <el-button @click="isNew = false">取消</el-button>
      <el-button type="primary" @click="saveContractWithOrder">提交</el-button>
    </div>
    </span>
  </div>
  <div v-else>
    <el-row justify="space-between">
      <!-- 搜索栏-->
      <el-col :span="10">
        <el-input
            v-model="cusName"
            placeholder="可输入签订合同的客户名称进行搜索"
            clearable
            @keyup.enter="search"
        >
        </el-input>
      </el-col>
      <el-col :span="10">
        <el-input
            v-model="empName"
            placeholder="可输入负责合同的销售人员名称进行搜索"
            clearable
            @keyup.enter="search"
        ></el-input>
      </el-col>
      <!-- 搜索按钮 -->
      <el-col :span="2">
        <el-button type="primary" icon="el-icon-search" @click="search" class="search-button">搜索</el-button>
      </el-col>
      <!--新增按钮-->
      <el-col :span="2">
        <el-button type="primary" @click="openAddPage">
          <el-icon>
            <Plus/>
          </el-icon>
          新增合同
        </el-button>
      </el-col>
    </el-row>
    <MessageBox2 :page-size="pageSize" :current-page="currentPage" :total="total" :table-data="contractStore.contracts"
                 :table-title-list="tableTitleList" :loading="loading" :table-title="tableTitle" :batch-mode="batchMode"
                 @current-change="currentPageChange" @size-change="pageSizeChange"
                 @selectionChange="updateSelectedRows">
      <template #title-btn>
        <el-button type="primary" @click="toggleBatchMode">
          {{ batchMode ? "取消批量操作" : "批量操作" }}
        </el-button>
        <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
            v-if="batchMode"
        >
          批量删除
        </el-button>
      </template>

      <template v-slot:table-btn>
        <!-- 显示合同状态的数字转换为文字 -->
        <el-table-column label="合同状态">
          <template #default="{row}">
            {{ getContractStatusText(row.contractStatus) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" show-overflow-tooltip>
          <template #default="{row}">
            <el-button icon="edit" circle plain type="warning" size="small" @click="openEditDialog(row)">编辑
            </el-button>
            <el-button icon="delete" circle plain type="danger" size="small" @click="deleteContract(row.contractId)">删除
            </el-button>
            <!--生成发货单按钮-->
            <el-button v-if="row.contractStatus!==2" icon="el-icon-s-order" round type="success" size="small"
                       @click="openOrderDialog(row)">生成发货单
            </el-button>
          </template>
        </el-table-column>
      </template>
    </MessageBox2>
  </div>

  <!--从订单生成进货单页面弹窗-->
  <el-dialog title="生成发货单" v-model="generateDeliveryDialogVisible" width="80%">
    <el-table :data="orderStore.orders" height="550" style="width: 100%" @row-click="handleProductRowClick">
      <el-table-column prop="orderId" label="订单编号" width="100"/>
      <el-table-column prop="productId" label="商品编号" width="100"/>
      <el-table-column prop="productName" label="商品名称" width="150"/>
      <el-table-column prop="quantity" label="合同签订商品数量" width="100"/>
      <el-table-column prop="price" label="商品单价" width="100"/>
      <el-table-column label="商品照片" width="180">
        <template #default="{row}">
          <el-image :src="row.productImg" style="width: 70px; height: 60px"/>
        </template>
      </el-table-column>
      <el-table-column prop="handCount" label="仓库余量" width="100"/>
      <!-- 新增的发货数量列 -->
      <el-table-column label="发货数量" width="180">
        <template #default="{row}">
          <el-input-number
              v-model="row.quantityShipped"
              :min="0"
              :max="row.quantity-row.payedCount"
              label="发货数量"
              style="width: 100%"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{row}">
          <el-button
              type="primary"
              size="small"
              @click="generateDeliveryNote(row)"
              :disabled="row.quantityShipped === 0">
            生成发货单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <!--新增合同选择客户弹窗-->
  <el-dialog title="选择客户" v-model="chooseCusDialogVisible" width="50%">
    <el-table :data="customerStore.customers" height="250" style="width: 100%" @row-click="handleRowClick">
      <el-table-column prop="cusId" label="客户编号" width="180"/>
      <el-table-column prop="cusName" label="客户姓名" width="180"/>
      <el-table-column prop="phone" label="客户电话" width="180"/>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelChooseCusDialog">取消</el-button>
      <el-button type="primary" @click="handleSelect">选择</el-button>
    </span>
  </el-dialog>

  <!--新增合同选择销售人员弹窗-->
  <el-dialog title="选择销售人员" v-model="chooseEmpDialogVisible" width="50%">
    <el-table :data="employeeStore.employees" height="250" style="width: 100%" @row-click="handleEmpRowClick">
      <el-table-column prop="empId" label="销售人员编号" width="180"/>
      <el-table-column prop="empName" label="销售人员姓名" width="180"/>
      <el-table-column prop="empPhone" label="销售人员电话" width="180"/>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelChooseEmpDialog">取消</el-button>
      <el-button type="primary" @click="handleEmpSelect">选择</el-button>
    </span>
  </el-dialog>

  <!--选择商品弹窗-->
  <el-dialog title="选择商品" v-model="chooseProductDialogVisible" width="65%">
    <el-table :data="productStore.products"
              ref="multipleTableRef"
              style="width: 100%"
              @selection-change="handleSelectionChange"
              highlight-current-row="true"
              height="580">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="productId" label="商品编号" width="180"/>
      <el-table-column prop="productName" label="商品名称" width="180"/>
      <el-table-column label="商品图片" width="180">
        <template #default="scope">
          <el-image :src="scope.row.productImg" :preview-src-list="[scope.row.productImg]"
                    style="width: 80px; height: 80px"/>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="商品价格" width="180"/>

      <!-- 添加商品数量列 -->
      <el-table-column label="商品数量" width="150">
        <template #default="scope">
          <el-input-number v-model="scope.row.quantity"
                           :min="1"
                           :max="1000"
                           label="商品数量"
                           style="width: 100%"
                           @change="handleSelectionChange"/>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <!--修改对话框-->
  <el-dialog title="编辑合同" v-model="editDialogVisible" width="30%">
    <el-form :model="editData" label-width="130px">
      <el-form-item label="合同编号" prop="contractId">
        <el-input v-model="editData.contractId" style="width: 200px" disabled/>
      </el-form-item>
      <el-form-item label="选择客户信息">
        <el-button type="primary" @click="openChooseCusDialog">选择客户</el-button>
      </el-form-item>
      <el-form-item label="客户编号">
        <el-input v-model="editData.cusId" style="width: 200px" disabled/>
      </el-form-item>
      <el-form-item label="客户姓名">
        <el-input v-model="editData.cusName" style="width: 200px" disabled/>
      </el-form-item>
      <el-form-item label="选择销售人员信息">
        <el-button type="primary" @click="openChooseEmpDialog">选择销售人员</el-button>
      </el-form-item>
      <el-form-item label="销售人员编号">
        <el-input v-model="editData.empId" style="width: 200px" disabled/>
      </el-form-item>
      <el-form-item label="销售人员姓名">
        <el-input v-model="editData.empName" style="width: 200px" disabled/>
      </el-form-item>
      <el-form-item label="合同状态">
        <el-input v-model="editData.contractStatus" style="width: 200px" disabled/>
      </el-form-item>
      <el-form-item label="合同签订时间">
        <el-date-picker
            v-model="editData.contractDate"
            type="date"
            placeholder="选择签订日期"
            value-format="YYYY-MM-DD"
            style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="合同截止时间">
        <el-date-picker
            v-model="editData.contractEndDate"
            type="date"
            placeholder="选择截止日期"
            value-format="YYYY-MM-DD"
            style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="合同订单">
        <el-button type="primary" @click="openProductDialog">查看商品</el-button>
      </el-form-item>
      <el-form-item label="合同备注">
        <el-input type="textarea" v-model="editData.remark" style="width: 200px"/>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取 消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确 定</el-button>
        </span>
    </template>
  </el-dialog>

  <!--查看商品对话框-->
  <el-dialog title="查看订单" v-model="productVisible" width="50%">
    <el-table v-if="!isEdit" :data="editData.saleOrders" height="540">
      <el-table-column prop="productId" label="商品编号" width="180"/>
      <el-table-column label="商品图片" width="180">
        <template #default="scope">
          <el-image :src="scope.row.productImg" :preview-src-list="[scope.row.productImg]"
                    style="width: 80px; height: 80px"/>
        </template>
      </el-table-column>
      <!--      <el-table-column prop="quantity" label="商品数量" width="180"/>-->
      <el-table-column label="商品数量">
        <template #default="scope">
          <el-input-number v-model="scope.row.quantity"
                           :min="1"
                           :max="1000"
                           label="商品数量"
                           style="width: 100%"
                           @change="handleSelectionChange"/>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="商品单价" width="180"/>
    </el-table>
    <el-table v-else :data="editData.products" height="540">
      <el-table-column prop="productId" label="商品编号" width="180"/>
      <el-table-column label="商品图片" width="180">
        <template #default="scope">
          <el-image :src="scope.row.productImg" :preview-src-list="[scope.row.productImg]"
                    style="width: 80px; height: 80px"/>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" width="150">
        <template #default="scope">
          <el-input-number v-model="scope.row.quantity"
                           :min="1"
                           :max="1000"
                           label="商品数量"
                           style="width: 100%"
                           @change="handleSelectionChange"/>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="商品单价" width="180"/>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="productVisible = false">取 消</el-button>
        <el-button type="primary" @click="productVisible = false">确 定</el-button>
        <el-button type="primary" @click="closeProductDialogAndOpenChoose">重新选择商品</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref, toRaw} from 'vue'
import MessageBox2 from "@/components/MessageBox2.vue";
import {contractsStore} from "@/stores/modules/contracts"
import {customersStore} from "@/stores/modules/customers"
import {employeesStore} from "@/stores/modules/employee"
import {productsStore} from "@/stores/modules/products"
import {ordersStore} from "@/stores/modules/order.js";
import {
  addContractService,
  deleteContractService,
  getContractPageListService,
  updateContractService
} from "@/api/contract"
import {getCustomerListService} from "@/api/customer"
import {getEmployeeListService} from "@/api/employee"
import {getProductListService} from "@/api/product"
import {getOrderByContractIdService} from "@/api/order"
import {generateSendOrderService} from "@/api/SendOrder.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 页面切换
const isNew = ref(false)


// 获取store 数据
const contractStore = contractsStore()
const employeeStore = employeesStore()
const customerStore = customersStore()
const productStore = productsStore()
const orderStore = ordersStore()

// 表格参数
const tableTitle = "合同信息"
const tableTitleList = {
  contractId: "合同编号",
  cusName: "客户名称",
  empName: "销售人员名称",
  contractDate: "合同签订日期",
  contractEndDate: "合同结束日期",
  remark: "合同备注"
}
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const cusName = ref('')
const empName = ref('')

// 合同状态映射
// const contractStatusOptions= [
//   { value: 1, label: '未履行' },
//   { value: 2, label: '已完成' },
//   { value: 3, label: '已取消' },
//   { value: 4, label: '履行中' }
// ]
const getContractStatusText = (status) => {
  const statusMap = {
    1: '未履行',
    2: '已完成',
    3: '已取消',
    4: '履行中'
  };
  return statusMap[status] || '未知状态'; // 如果没有匹配的状态，返回 '未知状态'
}

//页面变化 + 条件变化
const getContractPage = async (currentPage, pageSize, cusName, empName) => {
  loading.value = true

  console.log(currentPage, pageSize, cusName, empName)
  try {
    const res = await getContractPageListService(currentPage.value, pageSize.value, cusName.value, empName.value)
    console.log(res)
    if (res.status === 200) {
      contractStore.setContracts(res.data.data.records)
      total.value = res.data.data.total
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  } finally {
    loading.value = false
  }
}

// 查询函数
const search = () => {
  getContractPage(currentPage, pageSize, cusName, empName)
}

//子组件触发
const currentPageChange = (cP) => {
  currentPage.value = cP
  getContractPage(currentPage, pageSize, cusName, empName)
}
const pageSizeChange = (size) => {
  pageSize.value = size
  getContractPage(currentPage, pageSize, cusName, empName)
}

// 新增产品信息
const newContract = reactive({
  cusId: "",
  cusName: "",
  empId: "",
  empName: "",
  contractStatus: "",
  contractDate: "",
  contractEndDate: "",
  remark: "",
  products: []
})

// 新增页面切换
const openAddPage = () => {
  isNew.value = true
}

// 选择客户页面
const chooseCusDialogVisible = ref(false)
const openChooseCusDialog = async () => {
  chooseCusDialogVisible.value = true
  const res = await getCustomerListService()
  if (res.status === 200) {
    customerStore.setCustomers(res.data.data)
  } else {
    ElMessage.error('getCustomerListService请求出错')
  }
}
//取消选择
const cancelChooseCusDialog = () => {
  selectedCustomer.value = []
  chooseCusDialogVisible.value = false
}
// 删除选择
const deleteCustomer = (cusId) => {
  newContract.cusId = ""
  newContract.cusName = ""
  selectedCustomer.value = []
}

//新增合同中选择客户的数据
let selectedCustomer = ref([]);
const handleRowClick = (row) => {
  selectedCustomer.value = [row];
}
const handleSelect = () => {
  // 当用户点击“选择”按钮时，处理选中的数据
  if (selectedCustomer.value.length > 0) {
    // 这里可以进行进一步的处理，例如将选中的客户数据传递给父组件或关闭对话框
    newContract.cusId = selectedCustomer.value[0].cusId
    newContract.cusName = selectedCustomer.value[0].cusName
    editData.value.cusId = selectedCustomer.value[0].cusId
    editData.value.cusName = selectedCustomer.value[0].cusName
    chooseCusDialogVisible.value = false; // 关闭对话框
  } else {
    // 如果没有选中任何行，可以提示用户
    ElMessage.warning('请先选择一个客户');
  }
}

// 选择销售人员页面
const chooseEmpDialogVisible = ref(false)
const openChooseEmpDialog = async () => {
  chooseEmpDialogVisible.value = true
  try {
    const res = await getEmployeeListService()
    if (res.status === 200) {
      employeeStore.setEmployees(res.data.data)
    } else {
      ElMessage.error('getEmployeeListService请求出错')
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  }
}
// 取消选择
const cancelChooseEmpDialog = () => {
  selectedEmployee.value = []
  chooseEmpDialogVisible.value = false
}
// 删除销售人员的选择
const deleteEmployee = (empId) => {
  newContract.empId = ""
  newContract.empName = ""
  selectedEmployee.value = []
}

let selectedEmployee = ref([]);
const handleEmpRowClick = (row) => {
  selectedEmployee.value = [row];
}
const handleEmpSelect = () => {
  if (selectedEmployee.value.length > 0) {
    // 这里可以进行进一步的处理，例如将选中的员工数据传递给父组件或关闭对话框
    newContract.empId = selectedEmployee.value[0].empId
    newContract.empName = selectedEmployee.value[0].empName
    editData.value.empId = selectedEmployee.value[0].empId
    editData.value.empName = selectedEmployee.value[0].empName
    chooseEmpDialogVisible.value = false; // 关闭对话框
  } else {
    // 如果没有选中任何行，可以提示用户
    ElMessage.warning('请先选择一个员工');
  }
}


// 合同状态: 1待履行，2已完成，3已取消,4履行中
const contractStatusOptions = ref([
  {
    value: "1",
    label: '1待履行',
  },
  {
    value: '2',
    label: '2已完成',
  },
  {
    value: '3',
    label: '3已取消',
  },
  {
    value: '4',
    label: '4履行中',
  }
])

// 选择商品页面
const chooseProductDialogVisible = ref(false)
const openChooseProductDialog = async () => {
  chooseProductDialogVisible.value = true
  try {
    const res = await getProductListService()
    if (res.status === 200) {
      productStore.setProducts(res.data.data)
    } else {
      ElMessage.error('getProductListService请求出错失败')
    }
  } catch (e) {
    ElMessage.error('getProductListService请求出错')
  }
}
// 删除选择的商品
const deleteProduct = (productId) => {
  newContract.products = newContract.products.filter(product => product.productId !== productId)
}

// 行选择变化
const handleSelectionChange = (selectedRows) => {
  console.log('行选择变化')
  newContract.products = selectedRows.map(product => ({
    ...product,
    quantity: product.quantity || 1  // 设置商品的默认数量为 1
  }));
  // 将商品添加到编辑数据中
  editData.value.products = newContract.products
  isEdit.value = true
  console.log(editData.value.products)
  // toggleSelection(selectedRows)
}

// 新增合同保存
const saveContractWithOrder = async () => {
  try {
    const res = await addContractService(newContract)
    if (res.status === 200) {
      ElMessage.success('新增合同成功')
      await getContractPage(currentPage, pageSize, cusName, empName)
      isNew.value = false
    } else {
      ElMessage.error('新增失败')
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  }
}

//编辑合同
const editDialogVisible = ref(false)
const editData = ref({})
const isSaving = ref(false); // 用于保存按钮的加载状态
const openEditDialog = async (row) => {
  editData.value = {...row}
  try {
    const res = await getOrderByContractIdService(editData.value.contractId)
    if (res.status === 200) {
      editData.value.saleOrders = res.data.data
      orderStore.setOrders(res.data.data)
      console.log(editData.value)
      editDialogVisible.value = true
    }
  } catch (e) {
    ElMessage.error('请求出错')
  }
}

const handleEditConfirm = () => {
  // 判断合同状态是否为未履行状态
  if (editData.value.contractStatus !== 1) {
    editDialogVisible.value = false
    ElMessageBox.confirm(
        '请勿修改非未履行的合同',
        'error',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'error',
          center: true,
        }
    )
        .then(() => {
          ElMessage({
            type: 'success',
            message: 'Delete completed',
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: 'Delete canceled',
          })
        })
  } else {
    editContractAndOrder()
  }
}
const editContractAndOrder = async () => {
  try {
    isSaving.value = true;
    const res = await updateContractService(toRaw(editData.value))
    if (res.status === 200) {
      ElMessage.success('编辑客户成功')
      await getContractPage(currentPage, pageSize, cusName, empName)
      editDialogVisible.value = false
      isEdit.value = false
    } else {
      ElMessage.error('编辑失败')
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  } finally {
    isSaving.value = false;
    editDialogVisible.value = false
  }
}
const productVisible = ref(false)
const openProductDialog = () => {
  productVisible.value = true
}
const closeProductDialogAndOpenChoose = () => {
  productVisible.value = false
  openChooseProductDialog()
}
const isEdit = ref(false)
const cancelEdit = () => {
  editDialogVisible.value = false
  isEdit.value = false
}

// 批量删除客户
// 状态控制
const batchMode = ref(false); // 是否启用批量模式
const selectedRows = ref([]); // 存储选中的行数据
// 切换批量操作模式
const toggleBatchMode = () => {
  batchMode.value = !batchMode.value;
  if (!batchMode.value) {
    selectedRows.value = []; // 清空选中数据
  }
};
// 更新选中的行数据
const updateSelectedRows = (rows) => {
  selectedRows.value = rows;
};
// 批量删除逻辑
const handleBatchDelete = async () => {
  const ids = selectedRows.value.map((row) => row.contractId);
  try {
    const res = await deleteContractService(ids);
    if (res.status === 200) {
      contractStore.contracts = contractStore.contracts.filter(
          (item) => !ids.includes(item.contractId)
      );
      toggleBatchMode();
    }
  } catch (error) {
    console.error(error);
  }
  await getContractPage(currentPage, pageSize, cusName, empName)
};
//单个删除
const deleteContract = async (id) => {
  const res = await deleteContractService(id)
  if (res.status === 200) {
    contractStore.contracts = contractStore.contracts.filter(item => item.contractId !== id)
    ElMessage.success('删除成功')
  }
  await getContractPage(currentPage, pageSize, cusName, empName)
}


// 生成进货单 业务
const generateDeliveryDialogVisible = ref(false)
const openOrderDialog = async (row) => {

  try {
    const res = await getOrderByContractIdService(row.contractId)
    if (res.status === 200) {
      orderStore.setOrders(res.data.data)
      generateDeliveryDialogVisible.value = true
    }
  } catch (e) {
    await ElMessageBox.alert('请求出错')
  }
}

// 存储发货单
const sendOrders = ref([])
const generateDeliveryNote = async (row) => {
  // 判断发货数量是否大于0
  if (row.quantityShipped > 0) {
    // 将当前商品的相关信息存储到 sendOrders 中
    const orderData = {
      orderId: row.orderId,  // 订单编号
      productId: row.productId,  // 商品ID
      productName: row.productName,  // 合同签订商品数量
      quantityShipped: row.quantityShipped,  // 发货数量
    };

    // 将生成的订单数据推送到 sendOrders 数组中
    sendOrders.value.push(orderData);

    // 输出到控制台查看存储数据
    console.log('已生成发货单:', orderData);

    // 如果需要，你可以在这里添加更多的操作，例如调用接口等
    try {
      const res = await generateSendOrderService(orderData)
      console.log(res)
      if (res.status === 200) {
        await ElMessageBox.alert('已生成进货单', '提示', {})
        // 修改数据
        row.payedCount = row.payedCount + row.quantityShipped
        row.quantityShipped = 0
      } else {
        await ElMessageBox.alert('生成进货单失败', '提示', {})
      }
    } catch (e) {
      await ElMessageBox.alert('生成进货单失败', '提示', {})
    } finally {

    }
  }
}


// 初始化
console.log("初始化")
getContractPage(currentPage, pageSize, cusName, empName)
console.log("初始化结束")

</script>

<style scoped>
/*未使用*/
.box {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 5px;
  border: 2px solid #ccc;
  padding: 10px;
}

.custom-message {
  z-index: 9999;
}
</style>